package colaborativo.ondefica;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class SelectPoint extends Activity {	
	String nome;
	EditText nomeLocal;
	int mLoads = 0;
	Double X ,Y ;
	CheckBox chk;
	Boolean mod=false; 
	ArrayList<String> Lugares =  new ArrayList<String>();
	protected long ini_prs;
	protected int posX;
	protected int posY;
	private int reqCode;
	private String idPonto;
	private String local;
	private ListView listaLugares;	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_point);
		nomeLocal = (EditText) findViewById(R.id.searchLugar);
		listaLugares = (ListView) findViewById(R.id.listLugares);
		nomeLocal.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				new MyAsyncTask().execute("teste");
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});					
		
		Intent it = getIntent();
		Bundle extras = it.getExtras();
		if(extras!=null){
			Log.d("SP.Debug", extras.getDouble("xcenter")+"##############################"+extras.getDouble("ycenter"));
			X = extras.getDouble("xcenter");
			Y = extras.getDouble("ycenter");
		}
		
		new MyAsyncTask().execute("teste");		
	}	

	public void incluirLugar(View v){
		Intent intent = new Intent(this, IncludePoint.class);
		Bundle pontos = new Bundle();
		
		pontos.putDouble("xcenter", X);
		pontos.putDouble("ycenter", Y);
		intent.putExtras(pontos);			
		startActivityForResult(intent, reqCode);
		
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	  super.onActivityResult(requestCode, resultCode, data);
	  if (requestCode == reqCode && resultCode == RESULT_OK && data != null){
		  Bundle bd = data.getExtras();		  
		  idPonto = bd.getString("id");
		  local = bd.getString("nomeLocal");
		  nomeLocal.setText(local);
		  //listaLugares.
		  Lugares.add(local+":"+idPonto);
		  Log.d("SP.Load", local+":"+idPonto);
		// create the grid item mapping
		String[] from = new String[] {"nome"};
		int[] to = new int[] {R.id.textLocal};
		 
		        // prepare the list of all records
		List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
		for(String loc:Lugares){
		    HashMap<String, String> map = new HashMap<String, String>();		    
		    map.put("nome", loc);
		    fillMaps.add(map);
		}
		  
		SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.row, from, to);
        listaLugares.setAdapter(adapter);
        listaLugares.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(SelectPoint.this, CriarEvento.class);
				TextView txt = (TextView) arg1.findViewById(R.id.textLocal);
				
				intent.putExtra("LocalID", txt.getText().toString());
    			setResult(Activity.RESULT_OK, intent);
    			finish();
			}
		});
		adapter.notifyDataSetChanged();
      }
	     
	}
	
	
	
	
	public void salvarLugar(View v){
		Log.d("iP.SALVAR.Debug", "gogog");						
	}
	
	private void plot_points(JSONArray pontos){						
		
		
		
		String[] from = new String[] {"nome"};
		int[] to = new int[] {R.id.textLocal};
		 
		        // prepare the list of all records
		List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
		if(pontos!=null){
			Lugares.clear();
    		for(int i = 0;i<pontos.length();i++){
    			try{
    				Lugares.add(pontos.getJSONObject(i).getString("nomeLocal")+":"+pontos.getJSONObject(i).getInt("idLocal"));    				    				     				
    			}catch(JSONException e){				
    			}			
    		}
    		for(String loc:Lugares){
    		    HashMap<String, String> map = new HashMap<String, String>();		    
    		    map.put("nome", loc);
    		    fillMaps.add(map);
    		}  
    		SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.row, from, to);
            listaLugares.setAdapter(adapter);
            listaLugares.setOnItemClickListener(new OnItemClickListener() {
    			@Override
    			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
    					long arg3) {
    				Intent intent = new Intent(SelectPoint.this, CriarEvento.class);
    				TextView txt = (TextView) arg1.findViewById(R.id.textLocal);
    				
    				intent.putExtra("LocalID", txt.getText().toString());    			
        			setResult(Activity.RESULT_OK, intent);
        			finish();
    			}
    		});
    		adapter.notifyDataSetChanged();
		}
	}	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.include_point, menu);
		return true;
	}

	 private class MyAsyncTask extends AsyncTask<String, Integer, JSONArray>{
	    	@Override
	        protected JSONArray doInBackground(String... params) {	       
	        	mLoads++;
	        	String qry;
	        	if(!nomeLocal.getText().toString().isEmpty()){
	        		qry = "SELECT * FROM `geoPonto` WHERE `nomeLocal` LIKE '%"+nomeLocal.getText().toString()+"%'";
	        	}else{
	        		qry = "SELECT * FROM `geoPonto`";
	        	}
	    		Log.d("oM.pV.Query", qry);	    		
	    		return DbConnection.consulta(qry);	    				        
	        }
	         
	        protected void onPostExecute(JSONArray result){
//		        Log.d("oM.pV.resultado", jSarr.toString());	    		
	        	
	        	Log.d("oM.Ip.Result", "Acabou consulta");
	    			        	
	    		plot_points(result);		  
	        }
	        protected void onProgressUpdate(Integer... progress){
//	        	progress(progress[0]);
	        }
	        
	        
	    }
	 
	 //INSERT INTO `geoPonto`(`nomeLocal`, `latitute`, `longitude`, `idLocal`) VALUES ([value-1],[value-2],[value-3],NULL)	 
	 
}
